import { Component } from 'react';
import Taro from '@tarojs/taro';
import i18n, { l } from 'i18n-js';
import config from '@/app.config';
import { CoverView, CoverImage } from '@tarojs/components';
import { DynamicColors } from '@/utils/DarkMode';
import { getWxTabbarConfig } from '@/config/template';

import './index.scss';
import { reaction } from 'mobx';
import deviceData from '@/models/deviceData';
import deviceList from '@/models/deviceList';
import { isSameDevice } from '@/utils';
import { getLoginInfo } from '@/utils/loginStatus';

let isInit = false;

const isEqualPath = (a: string, b: string) => (a || '').replace(/^\//, '') === (b || '').replace(/^\//, '');

export default class Index extends Component {
  constructor(props) {
    super(props);
    const page = Taro.getCurrentInstance();
    let path = config.tabBar.list[0].pagePath;
    if (page && page.router) {
      path = page.router.path;
    }
    const list = config.tabBar.list;
    if (!isInit) {
      // 会多次触发构造
      const tabbar = getWxTabbarConfig() || {};
      if (tabbar) {
        tabbar.homeIcon ? (list[0].iconPath = tabbar.homeIcon) : (list[0].iconPath = `../${list[0].iconPath}`);
        tabbar.homeSelIcon
          ? (list[0].selectedIconPath = tabbar.homeSelIcon)
          : (list[0].selectedIconPath = `../${list[0].selectedIconPath}`);
        tabbar.mineIcon ? (list[1].iconPath = tabbar.mineIcon) : (list[1].iconPath = `../${list[1].iconPath}`);
        tabbar.mineSelIcon
          ? (list[1].selectedIconPath = tabbar.mineSelIcon)
          : (list[1].selectedIconPath = `../${list[1].selectedIconPath}`);
      }
      isInit = true;
    }

    this.state = {
      list,
      path,
      show: true,
    };

    const _this = this;
    wx.onAppRoute(function (res) {
      _this.setState({ path: res.path });
    });
  }

  alarmQueueReaction: any;

  switchTab(url) {
    console.log('switchTab', url);
    Taro.switchTab({ url: `/${url}` });
  }

  getValidAlarmData = alarmQueue => {
    const invalidAlarm: any[] = [];
    const validData = alarmQueue.find(i => {
      const { device } = i;
      if (device) {
        const deviceData = deviceList.data.find(d => isSameDevice(d, device));
        if (deviceData) {
          i.device = deviceData;
          return true;
        }
        // 告警的设备不在设备列表中，视为无效告警
        invalidAlarm.push(i);
      } else {
        invalidAlarm.push(i);
      }
      return false;
    });
    // 无效信息删除
    invalidAlarm.map(i => deviceData.delteAlarmInfo(i));
    return validData;
  };

  runAlarmQueue = alarmQueue => {
    if (alarmQueue && alarmQueue.length > 0) {
      const data = this.getValidAlarmData(alarmQueue);
      if (data) {
        this.setState({ show: false });
        return;
      }
    }
    this.setState({ show: true });
  };

  checkAlarmQueue = async alarmQueue => {
    if (global.token) {
      this.runAlarmQueue(alarmQueue);
    } else {
      const { token: isLogin } = await getLoginInfo();
      if (isLogin) {
        this.runAlarmQueue(alarmQueue);
      }
    }
  };

  componentDidMount() {
    this.alarmQueueReaction = reaction(
      () => ({ alarmQueue: deviceData.alarmQueue }),
      ({ alarmQueue }) => {
        this.checkAlarmQueue(alarmQueue);
      },
      { fireImmediately: true }
    );
  }

  componentWillUnmount(): void {
    this.alarmQueueReaction?.();
  }

  render() {
    const { list, path, show } = this.state;
    return (
      <CoverView className='tab-bar' style={{ opacity: show ? 1 : 0 }}>
        <CoverView className='tab-bar-border'></CoverView>
        {list.map((item, index) => {
          const isSelected = isEqualPath(path, item.pagePath);
          // console.log('url', item, isSelected);
          return (
            <CoverView key={index} className='tab-bar-item' onClick={this.switchTab.bind(this, item.pagePath)}>
              {isSelected ? <CoverImage src={`${item.selectedIconPath}`} /> : <CoverImage src={`${item.iconPath}`} />}
              <CoverView
                style={{ color: isSelected ? DynamicColors.tintColor.value : DynamicColors.normalTextColor.value }}>
                {i18n.t(item.text)}
              </CoverView>
            </CoverView>
          );
        })}
      </CoverView>
    );
  }
}
